home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8085 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: dawn.mmm.com!news
  2. From: kjhopps@mmm.com (Kevin J Hopps)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How do I overload 'char*' in my class. Is it possible?
  5. Date: 14 Feb 1996 13:16:33 GMT
  6. Organization: 3M - St. Paul, MN  55144-1000 US
  7. Distribution: world
  8. Message-ID: <4fsnbh$36j@dawn.mmm.com>
  9. References: <4fp80t$odj@alcor.usc.edu>
  10. Reply-To: kjhopps@mmm.com
  11. X-Newsreader: TIN [version 1.2 PL2]
  12.  
  13. Abu Wawda (wawda@alcor.usc.edu) wrote:
  14. > I wrote a string class and now I would like to overload: char*
  15. > (character pointer), but can't figure out how to do it. I've already
  16. > overloaded the +, +=, ==, =, and some operator operators, but can't
  17. > figure how to do this (or even if it's possible). Basically I want
  18. > something like:
  19.  
  20. >     char* operator ?? ()
  21.  
  22. > so that my string class can also return char*. Please help. Thanks,
  23.  
  24. You can provide a conversion operator, so that a string object is
  25. automatically converted:
  26.     operator const char*() const;
  27.  
  28. I added the const's so that it is illegal to modify the string
  29. through the pointer returned by the conversion.  The conversion
  30. works this way:
  31.     string s;
  32.     char a[256];
  33.     ...
  34.     strcpy(a, s);    // automatic conversion to const char*
  35.     strcpy(s, a);    // illegal: no conversion to char*
  36.  
  37. To allow this, the string class needs to guarantee a trailing
  38. null character is on the data.
  39.  
  40. You might also consider overloading operator[].
  41. --
  42. Kevin J. Hopps                  e-mail: kjhopps@mmm.com
  43. 3M Company                      phone:  (612) 737-4643
  44. 3M Center, Bldg. 235-2D-57      fax:    (612) 737-2700
  45. St. Paul, MN 55144-1000         Opinions are my own.  I don't speak for 3M.
  46.     But 3M speaks for me -- I did not write the following line:
  47.  
  48. Opinions expressed herein are my own and may not represent those of 3M.
  49.